#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"queue.h"

int queue_init(queue **myqueue, int capacity, int size){
	*myqueue = malloc(sizeof(queue));
	if(NULL == *myqueue)
		return -1;
	(*myqueue)->arr = malloc(size * capacity);
	if(NULL == (*myqueue)->arr){
		free(*myqueue);
		*myqueue = NULL;
		return -1;
	}

	(*myqueue)->size = size;
	(*myqueue)->capacity = capacity;
	(*myqueue)->front = (*myqueue)->tail = 0;

	return 0;
}

int queue_is_full(const queue *myqueue){
	return (myqueue->tail + 1) % myqueue->capacity == myqueue->front;
}

int queue_is_empty(const queue *myqueue){
	return myqueue->tail == myqueue->front;
}

int enqueue(queue *myqueue, const void *data){
	if(queue_is_full(myqueue))
		return -1;
	memcpy((char *)myqueue->arr + myqueue->size * myqueue->tail, data, myqueue->size);
	myqueue->tail = (myqueue->tail + 1) % myqueue->capacity;

	return 0;
}

int dequeue(queue *myqueue, void *data){
	if(queue_is_empty(myqueue))
		return -1;
	memcpy(data, (char *)myqueue->arr + myqueue->front * myqueue->size, myqueue->size);
	myqueue->front = (myqueue->front + 1) % myqueue->capacity;

	return 0;
}

void queue_destroy(queue **myqueue){
	free((*myqueue)->arr);
	(*myqueue)->arr = NULL;

	free(*myqueue);
	*myqueue = NULL;
}


